<template>
  <msg-box :message="message">
    <!-- 语音消息  -->
    <view class="voice-message" @tap="playVoice(content)">
      <view class="voice-icon" :class="{ playing: isPlaying }">
        <view class="chatIcon icon-shengyin" style="font-size: 48rpx"></view>
      </view>
      <text> {{ formatTimePlay(message.content?.duration) }} </text>
      <text style="font-size: 24rpx; color: #999">语音消息</text>
    </view>
  </msg-box>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import msgBox from "./msg-box.vue";
import { formatTimePlay } from "../../utils/utils";

// 监听消息变化
const message = defineModel("message", {
  type: Object,
  required: false,
  default: () => ({}),
});

// 解析消息
const content = computed((): string => {
  return message.value?.content?.url || message.value?.content || "";
});

const isPlaying = ref(false);
const innerAudioContext = uni.createInnerAudioContext();

// 监听可以播放
innerAudioContext.onCanplay((res) => {
  console.log("innerAudioContext.onCanplay -> res", res);
});

// 监听播放结束
innerAudioContext.onEnded(() => {
  isPlaying.value = false;
});

// 监听播放错误
innerAudioContext.onError(() => {
  isPlaying.value = false;
});

// 播放语音
const playVoice = (url: string) => {
  if (isPlaying.value) {
    innerAudioContext.pause();
    isPlaying.value = false;
    return;
  }
  innerAudioContext.src = url;
  isPlaying.value = true;
  innerAudioContext.play();
};
</script>
<style scoped lang="scss">
.voice-message {
  display: flex;
  align-items: center;
  gap: 10rpx;

  .voice-icon {
    transition: all 0.3s ease;
    color: #464646;

    &.playing {
      animation: voicePlay 1s infinite ease;
    }
  }
}

@keyframes voicePlay {
  0% {
    text-shadow: 0 0 10rpx rgba(100, 250, 255, 0.5);
    color: #3d9bff;
  }
  50% {
    text-shadow: 0 0 10rpx rgba(35, 174, 255, 0.5);
  }
  100% {
    text-shadow: 0 0 10rpx rgba(68, 255, 139, 0.5);
    color: #5b87b6;
  }
}
</style>
